package prototyping;

import java.rmi.RMISecurityManager;
import net.jini.core.discovery.LookupLocator;
import net.jini.core.entry.Entry;
import net.jini.core.lease.Lease;
import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.lookup.entry.Name;
import net.jini.space.JavaSpace;

public class TestJSpace {
	static public JavaSpace findSpace(String spaceName) throws Exception {
		// Get a RMI security manger, if doesn't exist set a new one.
		// The security policy is passed to this security manager using the
		// -Djava.security.policy flag.
		if (System.getSecurityManager() == null)
			System.setSecurityManager(new RMISecurityManager());

		// Create a template to lookup the JavaSpaces service.
		Class[] classes = new Class[] { net.jini.space.JavaSpace.class };
		Name sn = new Name(spaceName);
		ServiceTemplate tmpl = new ServiceTemplate(null, classes,
				new Entry[] { sn });

		// Locate the JavaSpaces service and create a JavaSpace proxy attached
		// to it.
		LookupLocator locator = new LookupLocator("jini://localhost");
		ServiceRegistrar sr = locator.getRegistrar();
		JavaSpace space = (JavaSpace) sr.lookup(tmpl);

		return space;
	}

	public static void main(String[] args) {
		try {
			MyEntry msg = new MyEntry();
			msg.content = "Hello World";

			JavaSpace space = findSpace("test1");
			space.write(msg, null, Lease.FOREVER);

			MyEntry template = new MyEntry();
			MyEntry result = (MyEntry) space.read(template, null,
					Long.MAX_VALUE);
			System.out.println(result.content);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
